import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi

class PaymentQueryListApi(BaseApi):
    def execute(self, order_no, payment_amount, wait_payment_data_no, user_id, business_type=1, sub_bus_type=20000):
        """
        查询支付方式列表API
        
        Args:
            order_no: 订单号
            payment_amount: 支付金额
            wait_payment_data_no: 等待支付数据号
            user_id: 用户ID
            business_type: 业务类型，默认1
            sub_bus_type: 子业务类型，默认20000
            
        Returns:
            dict: 包含以下字段的字典：
                - title: 标题
                - tip: 提示信息
                - confirmBtn: 确认按钮文本
                - amount: 支付金额
                - payList: 支付方式列表，每个支付方式包含：
                    - channelId: 渠道ID
                    - channelName: 渠道名称
                    - channelLogo: 渠道Logo
                    - balance: 余额（如果有）
                    - checked: 是否选中
                    - showGray: 是否显示灰色
                    - tip: 提示信息（如果有）
        """
        url = f"{self.BASE_URL}/api/youpin/bff/payment/v1/cashier/query/list"
        data = {
            "businessType": business_type,
            "extend": "{\"appInstall\":false}",
            "orderNo": order_no,
            "paymentAmount": str(payment_amount),
            "subBusType": sub_bus_type,
            "userId": user_id,
            "waitPaymentDataNo": wait_payment_data_no,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"API返回错误: {result.get('msg', '未知错误')}")
                return None
            data = result.get('data', {})
            return {
                'title': data.get('title'),
                'tip': data.get('tip'),
                'confirmBtn': data.get('confirmBtn'),
                'amount': data.get('amount'),
                'payList': [{
                    'channelId': pay.get('channelId'),
                    'channelName': pay.get('channelName'),
                    'channelLogo': pay.get('channelLogo'),
                    'balance': pay.get('balance'),
                    'checked': pay.get('checked'),
                    'showGray': pay.get('showGray'),
                    'tip': pay.get('tip')
                } for pay in data.get('payList', [])]
            }
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None


def main():
    """测试支付方式查询API"""
    try:
        # 使用实际的认证信息
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
        
        if not account:
            print("无法获取ID为1的账号")
            return
        
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = PaymentQueryListApi(
            device_token=device_id,  # 使用 device_id 作为 device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 调用API
        result = api.execute(
            order_no="2025020210964679356",
            payment_amount="0.07",
            wait_payment_data_no="202502021678799221",
            user_id="9534592"
        )
        
        # 打印结果
        print("\n=== 支付方式查询API测试结果 ===")
        if result is None:
            print("支付方式查询失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"标题: {result['title']}")
            print(f"提示: {result['tip']}")
            print(f"确认按钮: {result['confirmBtn']}")
            print(f"支付金额: {result['amount']}")
            print("\n支付方式列表:")
            for pay in result['payList']:
                print(f"\n- {pay['channelName']}:")
                print(f"  渠道ID: {pay['channelId']}")
                print(f"  余额: {pay['balance']}")
                print(f"  是否选中: {'是' if pay['checked'] else '否'}")
                print(f"  Logo: {pay['channelLogo']}")
                if pay['tip']:
                    print(f"  提示: {pay['tip']}")
    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
